package server.proxy;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import logger.CLoggerFactory;

import org.apache.log4j.Logger;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.http.HttpMessage;

/**
 * This class scans the sent and received data and logs all the mail records in this data to the mail log file.
 * 
 * @author Maxim
 *
 */
public class ProxyServerMailListHandler extends SimpleChannelUpstreamHandler {
	
	Logger _logger;
	
	public ProxyServerMailListHandler() throws IOException{
		this._logger = CLoggerFactory.getFileLogger("mail_list_received", Config.MAIL_LIST_FILE_NAME);
	}
	
	
	
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception{
		
		String tMailList = mailListIhThisHttpRequest((HttpMessage)e.getMessage());
		
		if(tMailList.length()>1)
			this._logger.info(mailListIhThisHttpRequest((HttpMessage)e.getMessage()));
		
		ctx.sendUpstream(e);
		
		
	}
	
	
	@Override
    public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {
        // Add all open channels to the global group so that they are
        // closed on shutdown.
       
    	ProxyServer.allChannels.add(e.getChannel());
    }
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		
		System.out.println("Unexpected exception from proxy server mail list handler: " + e.getCause());
		e.getChannel().close();
	}

	
	
	/**
	 * This method scans the data and the headers inside the HTTP message and return all the email's in this data.
	 * @param httpMessage
	 * @return
	 * 
	 */
	private String mailListIhThisHttpRequest(HttpMessage httpMessage){
		
		String tAnswer="";
		String patternStr = "\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}\\b";
		Pattern pattern = Pattern.compile(patternStr);
	
		StringBuilder sb = new StringBuilder();
		for (java.util.Map.Entry<String, String> entry : httpMessage.getHeaders()) {
		   sb.append(entry.getKey() + " = " + entry.getValue() + "\n");
		 }
		
		
		sb.append(httpMessage.getContent().toString(Charset.defaultCharset()));
		 
		
        Matcher matcher = pattern.matcher(httpMessage.getContent().toString(Charset.defaultCharset()) + sb.toString());
        
        while(matcher.find()){
        	
        	tAnswer+= matcher.group()+"\n";
        }
        
		return tAnswer;
	}
}
